﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace InstitutionAssitant
{
    public partial class frmSupervisionUpload : DevComponents.DotNetBar.OfficeForm
    {
        #region 01.自定义属性
        int m_nFieldSelectedOrder = 1;  // 选择列所在顺序位置(0为起始列)
        public Boolean m_bIsSelectBegin = false;    //多选时用        
        public DataTable m_dt;  // 保存查询出来的数据
        private string strJson;    // 查询条件
        public string _SuppervisionAPICode = "",_AppKey="", _AppSecret="";
        #endregion
        public frmSupervisionUpload()
        {
            InitializeComponent();
        }
        #region 02.自定义方法
        public void _initDgvTitle()
        {
            string strInfo = "";
            string strKind = "";
            // 01 frmLocalOrder
            strKind = this.Name;
            // 存在时不再处理
            if (AppConfig.m_dictFieldName.ContainsKey(strKind))
            {
                return;
            }
            strInfo = "ID-序号,BillCode-订单号,BillCodeDetail-订单明细号,SupplierName-配送企业名称,Product_Seq_No-商品编码,Physic_Name-商品名称,Package_Spec-规格,Preparations_Unit-单位,Product_Ent_Name-厂家,Produce_Batch_No-批号,MakeDate-生产日期,ExperidDate-有效日期,OperateUserId-操作人ID,OperateUserName-操作人,OperateCreateTime-操作时间,UploadStatus-状态,UploadStatusStr-上传状态,UploadTime-上传日期,FromEntId-配企编号,ToEntId-医疗机构编号,BillType-订单类型,BillTime-订单时间,PhysicType-商品类型,TraceCodes-监管码";
            AppConfig.m_dictFieldName.Add(strKind, strInfo);
            strInfo = "ID,BillCode,BillCodeDetail,SupplierName,Product_Seq_No,Physic_Name,Package_Spec,Preparations_Unit,Product_Ent_Name,Produce_Batch_No,MakeDate,ExperidDate,OperateUserId,OperateUserName,OperateCreateTime,UploadStatus,UploadStatusStr,UploadTime,FromEntId,ToEntId,BillType,BillTime,PhysicType,TraceCodes";
            AppConfig.m_dictFieldSql.Add(strKind, strInfo);
            // 与SqlField同
            AppConfig.m_dictField0.Add(strKind, strInfo);
            AppConfig.m_dictField.Add(strKind, strInfo);
            strInfo = "0,160,0,160,80,160,80,80,160,80,80,80,0,80,0,0,80,100,0,0,0,0,0,0";
            AppConfig.m_dictFieldWidth0.Add(strKind, strInfo);
            AppConfig.m_dictFieldWidth.Add(strKind, strInfo);

            strKind = this.Name + "1";
            // 存在时不再处理
            if (AppConfig.m_dictFieldName.ContainsKey(strKind))
            {
                return;
            }
            strInfo = "SupervisionCode_Up-追溯码,PackageRatio-包装比";
            AppConfig.m_dictFieldName.Add(strKind, strInfo);
            strInfo = "SupervisionCode_Up,PackageRatio";
            AppConfig.m_dictFieldSql.Add(strKind, strInfo);
            strInfo = "SupervisionCode_Up,PackageRatio";
            AppConfig.m_dictField0.Add(strKind, strInfo);
            AppConfig.m_dictField.Add(strKind, strInfo);
            strInfo = "160,60";
            AppConfig.m_dictFieldWidth0.Add(strKind, strInfo);
            AppConfig.m_dictFieldWidth.Add(strKind, strInfo);            
        }
        private void ShowSupervisionCode(DataGridViewRow dgvr)
        {
            string TraceCodes = dgvr.Cells["TraceCodes"].Value.ToString();
            string[] CodesArr = TraceCodes.Split(',');
            string CodeTemp = "";
            if (CodesArr.Length > 0)
            {
                for (int i = 0; i < CodesArr.Length; i++)
                {
                    if (i == 0)
                        CodeTemp += "'" + CodesArr[i] + "'";
                    else
                        CodeTemp += ",'" + CodesArr[i] + "'";
                }
                //CodeTemp += ")";
                // 取溯源码数据
                string strSql = "select SupervisionCode,SupervisionCode_Up,PackageRatio from TH_PlatformSupervisionCode where SupervisionCode in ({0}) or SupervisionCode_Up in ({0})";
                strSql = string.Format(strSql, CodeTemp);
                DataTable dt = DbHelper.DBAccess[0]._openSql_Dt(strSql);
                DataTable dtview = new DataTable();
                dtview.Columns.Add("SupervisionCode_Up", typeof(string));
                dtview.Columns.Add("PackageRatio", typeof(string));
                if(dt.Rows.Count>0)
                {
                    foreach(DataRow dr in dt.Rows)
                    {
                        DataRow row = dtview.NewRow();
                        row["PackageRatio"] = dr["PackageRatio"].ToString();
                        if (string.IsNullOrEmpty(dr["SupervisionCode_Up"].ToString()))
                        {                            
                            row["SupervisionCode_Up"] = dr["SupervisionCode"].ToString();                            
                        }
                        else
                            row["SupervisionCode_Up"] = dr["SupervisionCode_Up"].ToString();
                        dtview.Rows.Add(row);
                    }
                }
                // 显示数据
                CommFun._showDataGridView0(dataGridViewX2, dtview, AppConfig.m_dictFieldWidth[this.Name + "1"], AppConfig.m_dictFieldName[this.Name + "1"]);
            }
        }
        private void _init()
        {
            // 01 dataGridViewX1设为不可编辑
            dataGridViewX1.ReadOnly = true;
            dataGridViewX1.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top));
            dataGridViewX2.ReadOnly = true;
            dataGridViewX2.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top));
            // 02 初始化日期
            dtpDateBegin.Format = DateTimePickerFormat.Custom;
            dtpDateBegin.CustomFormat = "yyyy-MM-dd";
            dtpDateEnd.Format = dtpDateBegin.Format;
            dtpDateEnd.CustomFormat = dtpDateBegin.CustomFormat; 
            dtpDateEnd.Value = DateTime.Now;
            dtpDateBegin.Value = dtpDateEnd.Value.AddDays(AppConfig.m_nDateBeforeDistribution * -1);
            
            
            // 05 DataGridView
            _initDgvTitle();
            cbbUploadSta.SelectedIndex = 0;
            string strSql = "select Code,AppKey,AppSecret from MSFX_Enterprise where Name='{0}'";
            strSql = string.Format(strSql, AppInfo.m_UserInfo.m_strDeptName);
            DataTable dt1 = DbHelper.DBAccess[0]._openSql_Dt(strSql);
            if (dt1 != null)
            {
                _SuppervisionAPICode = dt1.Rows[0]["Code"].ToString();
                _AppKey = dt1.Rows[0]["AppKey"].ToString();
                _AppSecret = dt1.Rows[0]["AppSecret"].ToString();
            }
            else
            {
                CommFun._messageBoxShow(string.Format("未获取到当前单位的API参数！"), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //_query();
        }
        private void _query()
        {
            if (m_dt != null)
            {
                m_dt.Dispose();
            }
            string _beginDate = "", _endDate = "", _goodsname = "", _billcode = "", _uploadsta = "";  
            strJson = "{\"rows\":100,\"page\":1}";
            SupervisionApiJson SAJ = new SupervisionApiJson();
            SAJ.pagination = strJson;            
            // 02 取配送日期
            if (cbDate.Checked)
            {
                if (dtpDateBegin.Value.ToString("yyyy-MM-dd").CompareTo(dtpDateEnd.Value.ToString("yyyy-MM-dd")) > 0)
                {
                    CommFun._messageBoxShow(string.Format("起始日期大于终止日期！"), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    _beginDate = dtpDateBegin.Value.ToString("yyyy-MM-dd");
                    _endDate = dtpDateEnd.Value.AddDays(1).ToString("yyyy-MM-dd");
                }
            }
            // 05 商品名称
            if (cbGoodsName.Checked)
            {
                _goodsname = txtGoodsName.Text.Trim();
            }
            // 05 出库单号
            if (cbBillCode.Checked)
            {
                _billcode = txtBillCode.Text.Trim();
            }
            //11 上传状态
            if (cbUploadSta.Checked)
            {
                _uploadsta = cbbUploadSta.SelectedIndex.ToString();
            }
            //strJson = "{\"Ent_Id\":\""+ _SuppervisionAPICode + "\",\"UploadStatus\":\""+ _uploadsta + "\",\"BillCode\":\"" + _billcode + "\",\"BeginDate\":\""+ _beginDate + "\",\"EndDate\":\""+ _endDate + "\",\"keyword\":\""+ _goodsname + "\"}";
            strJson = "{\"Ent_Id\":\"2c9194c61e498df3011e5dd5b3ae47e7\",\"UploadStatus\":\"" + _uploadsta + "\",\"BillCode\":\"" + _billcode + "\",\"BeginDate\":\"" + _beginDate + "\",\"EndDate\":\"" + _endDate + "\",\"keyword\":\"" + _goodsname + "\"}";
            SAJ.queryJson = strJson;
            strJson = JsonConvert.SerializeObject(SAJ);
            //strJson = string.Format(strJson, AppInfo.m_UserInfo.m_strDeptCode, _billcode, _beginDate, _endDate, _goodsname);
            //调用接口查询数据
            string url = DbHelper._getSupervisionAddress();// + "DrugTracePurchaseInstore";
            if (!url.Equals("") && !url.Equals("http://"))
            {
                url += "/Msfx/GetUploadHospitalStockPageList";
                string resCode = HisInterFace.Post(url, strJson);
                string files = AppDomain.CurrentDomain.BaseDirectory + "\\DBlog\\SuUp" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                FileSystemObject.Create(files, FsoMethod.File);
                FileSystemObject.WriteFile(files, "url:" + url + "\r\n");
                FileSystemObject.WriteFile(files, "para:" + strJson + "\r\n", true);
                FileSystemObject.WriteFile(files, "result:" + resCode + "\r\n", true);

                JObject jo = (JObject)JsonConvert.DeserializeObject(resCode);
                int resCode1 = int.Parse(jo["code"].ToString());

                if(resCode1==200)
                {
                    string dataJson = jo["data"]["rows"].ToString();
                    DataTable dt = JsonConvert.DeserializeObject<DataTable>(dataJson); // 使用JsonConvert.DeserializeObject方法将JSON字符串转换为DataTable对象
                    _doData(dt);
                     // 03 显示数据                
                    _showData(dt);
                }                
            }
            else
            {
                CommFun._messageBoxShow("码上放心接口地址未设置！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void _doData(DataTable dt)
        {
            if (dt != null)
            {
                dt.Columns.Add("SupplierName", typeof(string));
                dt.Columns.Add("UploadStatusStr", typeof(string));
                foreach(DataRow dr in dt.Rows)
                {
                    string strSql = "select SupplierName from MSFX_Supplier where SupplierCode='{0}'";
                    strSql = string.Format(strSql, dr["FromEntId"].ToString());
                    DataTable dtName=DbHelper.DBAccess[0]._openSql_Dt(strSql);
                    if (dtName != null && dtName.Rows.Count > 0)
                    {
                        dr["SupplierName"] = dtName.Rows[0]["SupplierName"].ToString();
                    }
                    dr["UploadStatusStr"] = dr["UploadStatus"].ToString() == "0" ? "未传" : "已传";
                }
            }
        }
        private void _showData(DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                // 0101 调整字段顺序
                CommFun._dataTableFieldMove(dt, AppConfig.m_dictField[this.Name]);
                // 0102 显示数据
                CommFun._showDataGridView0(dataGridViewX1, dt, AppConfig.m_dictFieldWidth[this.Name], AppConfig.m_dictFieldName[this.Name], true, false);                
            }
            else
            {
                // 清除数据
                DataTable dtTemp = (DataTable)dataGridViewX1.DataSource;
                if (dtTemp != null && dtTemp.Rows.Count > 0)
                {
                    dtTemp.Rows.Clear();
                }
            }            
        }
        /// <summary>
        /// 设置全选或全不选
        /// </summary>
        /// <param name="nKind">1：全选 0：全不选</param>
        private void _SelectAll(int nKind)
        {
            if (dataGridViewX1.Rows.Count > 0)
            {
                this.dataGridViewX1.CurrentCell = null; // 设置当前列，因为如当前列在选择列时，会出现不能设置数据情况
                foreach (DataGridViewRow row in dataGridViewX1.Rows)
                {
                    row.Cells[m_nFieldSelectedOrder].Value = nKind;
                }
            }
        }
        /// <summary>
        /// 取选中的数据项信息,倒排方式,当nKind==0时,需去除未选数据
        /// </summary>
        /// <param name="nKind">0:去除未选项 1:取已先数据编号</param>
        private string _GetSelectedInfo(int nKind = 0)
        {
            // 01 去除未选项
            string strResult = "";
            string strID = "";
            for (int i = dataGridViewX1.Rows.Count - 1; i >= 0; i--)
            {
                strID = dataGridViewX1.Rows[i].Cells["IsSelected"].Value.ToString();
                if (!strID.Equals("1"))
                {
                    if (nKind == 0)
                    {
                        //0:去除未选项
                        dataGridViewX1.Rows.RemoveAt(i);
                    }
                }
                else
                {
                    strResult += (strResult.Equals("") ? "" : ",") + dataGridViewX1.Rows[i].Cells["ID"].Value.ToString();
                }
            }
            // 显示行号
            CommFun._formatHeaderCell(dataGridViewX1);            
            return strResult;
        }
        #endregion

        #region GridViewX事件

        private void dataGridViewX1_ColumnHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            // 选择列标题双击操作
            DataGridViewColumn newColumn = ((DataGridView)sender).Columns[e.ColumnIndex];
            if (e.ColumnIndex == m_nFieldSelectedOrder)
            {
                // 判定当前全选或未选状态
                if (newColumn.HeaderText.Contains("☑"))
                {
                    newColumn.HeaderText = "□";
                    //_SelectAll(0);
                }
                else
                {
                    newColumn.HeaderText = "☑";
                    //_SelectAll(1);
                }
            }
            else
            {
                // 排序
                CommFun._dgvColumnHeaderSort(sender, e);
               // _showSpecRow();
            }
        }

        private void dataGridViewX1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            // 鼠标拖动多选时用:确定起始单元格
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                m_bIsSelectBegin = false;
                return;
            }
            // 只是单选框时作多项选择操作(鼠标按下不放多选)
            DataGridViewColumn newColumn = ((DataGridView)sender).Columns[e.ColumnIndex];
            // 判断是否可编辑列
            if (newColumn.DataPropertyName.Equals("IsSelected"))
            {
                m_bIsSelectBegin = true;
            }
            else
            {
                m_bIsSelectBegin = false;
            }
        }

        private void dataGridViewX1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            // 鼠标拖动多选时用:确定结束单元格
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                m_bIsSelectBegin = false;
                return;
            }
            // 只是单选框时作多项选择操作(鼠标按下不放多选)
            DataGridViewColumn newColumn = ((DataGridView)sender).Columns[e.ColumnIndex];
            if (newColumn.DataPropertyName.Equals("IsSelected") && m_bIsSelectBegin)
            {
                foreach (DataGridViewCell item in ((DataGridView)sender).SelectedCells)
                {
                    if (item.ColumnIndex == m_nFieldSelectedOrder)
                    {
                        if (((item.Value == null) ? "0" : item.Value.ToString()) == "1")
                        {
                            item.Value = 0;
                        }
                        else
                        {
                            item.Value = 1;
                        }
                    }
                }
            }
        }

        

        private void dataGridViewX1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            // 改变行颜色
            CommFun._dgvRowEnter(sender, e);

        }
        private void dataGridViewX1_SelectionChanged(object sender, EventArgs e)
        {
            if (this.dataGridViewX1.SelectedRows.Count > 0)
            {
                // 获取当前选中的行
                DataGridViewRow selectedRow = this.dataGridViewX1.SelectedRows[0];
                //显示该行数据到右侧详情
                ShowSupervisionCode(selectedRow);
            }
        }

        #endregion

        #region 系统事件             

        private void buttonX1_Click(object sender, EventArgs e)
        {
            //数据上传
            // 01 取选择的数据项
            string strInfoID = _GetSelectedInfo(1);
            if (strInfoID.Equals(""))
            {
                CommFun._messageBoxShow("请先确定要上传的数据!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            // 03 上传处理
            bool bOK = true;
            DataTable dt = (DataTable)dataGridViewX1.DataSource;
            DataView dv = dt.DefaultView;
            dv.RowFilter = string.Format("ID in ({0})", strInfoID);
            DataTable dt1 = dv.ToTable(true);
            foreach (DataRow dr in dt1.Rows)
            {
                if (dr["UploadStatus"].ToString().Equals("1"))
                {
                    DialogResult dre = CommFun._messageBoxShow("有记录已上传!", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    if (dre == DialogResult.Cancel)
                    {
                        bOK = false;
                        break;
                    }
                }
                if (!bOK)
                {
                    return;
                }
                UploadSuppervision(dr);
            }
        }

        private void btnQuery_Click_1(object sender, EventArgs e)
        {
            // 数据查询
            _query();
        }

        private void UploadSuppervision(DataRow dr)
        {
            string strJson = "{";
            strJson += "\"BillCode\":\""+dr["BillCode"].ToString()+"\",";
            strJson += "\"BillDetailCode\":\"" + dr["BillCodeDetail"].ToString() + "\",";
            strJson += "\"Physic_Name\":\"" + dr["Physic_Name"].ToString() + "\",";
            strJson += "\"Package_Spec\":\"" + dr["Package_Spec"].ToString() + "\",";
            strJson += "\"Package_Spec\":\"" + dr["Package_Spec"].ToString() + "\",";
            strJson += "\"Preparations_Unit\":\"" + dr["Preparations_Unit"].ToString() + "\",";
            strJson += "\"Product_Seq_No\":\"" + dr["Product_Seq_No"].ToString() + "\",";
            strJson += "\"Produce_Batch_No\":\"" + dr["Produce_Batch_No"].ToString() + "\",";
            strJson += "\"Product_Ent_Name\":\"" + dr["Product_Ent_Name"].ToString() + "\",";
            strJson += "\"Approval_No\":\"" + dr["Approval_No"].ToString() + "\",";
            strJson += "\"MakeDate\":\"" + dr["MakeDate"].ToString() + "\",";
            strJson += "\"ExperidDate\":\"" + dr["ExperidDate"].ToString() + "\",";
            strJson += "\"BillType\":" + dr["BillType"].ToString() + ",";
            strJson += "\"BillTime\":\"" + dr["BillTime"].ToString() + "\",";
            strJson += "\"RefUserId\":\"" + _SuppervisionAPICode + "\",";
            strJson += "\"FromEntId\":\"" + dr["FromEntId"].ToString() + "\",";
            strJson += "\"ToEntId\":\"" + dr["ToEntId"].ToString() + "\",";
            strJson += "\"PhysicType\":" + dr["PhysicType"].ToString() + ",";
            strJson += "\"TraceCodes\":\"" + dr["TraceCodes"].ToString() + "\",";
            strJson += "\"Ent_Id\":\"" + _SuppervisionAPICode + "\",";
            strJson += "\"OperateUserId\":\"" + dr["OperateUserId"].ToString() + "\",";
            strJson += "\"OperateUserName\":\"" + dr["OperateUserName"].ToString() + "\",";
            strJson += "\"OperateCreateTime\":\"" + dr["OperateCreateTime"].ToString() + "\",";
            strJson += "\"AppKey\":\"" + _AppKey + "\",";
            strJson += "\"AppSecret\":\"" + _AppSecret + "\"";
            strJson += "}";
            //调用接口查询数据
            string url = DbHelper._getSupervisionAddress();
            if (!url.Equals("") && !url.Equals("http://"))
            {
                url += "/Msfx/UploadHospitalStockList";
                string resCode = HisInterFace.Post(url, strJson);
                string files = AppDomain.CurrentDomain.BaseDirectory + "\\DBlog\\SuUp" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                FileSystemObject.Create(files, FsoMethod.File);
                FileSystemObject.WriteFile(files, "url:" + url + "\r\n");
                FileSystemObject.WriteFile(files, "para:" + strJson + "\r\n", true);
                FileSystemObject.WriteFile(files, "result:" + resCode + "\r\n", true);

                JObject jo = (JObject)JsonConvert.DeserializeObject(resCode);
                int resCode1 = int.Parse(jo["code"].ToString());

                if (resCode1 == 200)
                {
                    CommFun._messageBoxShow(jo["info"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                CommFun._messageBoxShow("码上放心接口地址未设置！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void frmSupervisionUpload_Load(object sender, EventArgs e)
        {
            _init();
        }
        #endregion

    }

    public class SupervisionApiJson
    {
        public string pagination { get; set; }
        public string queryJson { get; set; }
    }
}
